import numpy as np
import image_io
from image_utils import logging


def split_image_channels(image):
    '''
    该函数用于分割图像的颜色通道
    :param image: 输入图像，numpy数组
    :return: 图像的颜色通道列表
    '''
    try:
        logging.info("开始分割图像颜色通道")

        if image.ndim < 3:
            raise ValueError("图像通道数必须大于等于2")

        channel_list = np.split(image, image.shape[-1], axis=-1)
        channel_list = [np.squeeze(channel) for channel in channel_list]

        logging.info(f"成功分割图像颜色通道")
        return channel_list
    except Exception as e:
        raise ValueError(f"在分割图像颜色通道时发生错误： {e}")


def merge_image_channels(file_paths):
    '''
    该函数用于合并多个单通道图像，创建一个多通道图像
    :param file_paths: 包含单通道图像文件路径的列表
    :return: 合并后的多通道图像
    '''
    try:
        logging.info("开始合并图像通道")

        images = [image_io.read(file_path) for file_path in file_paths]
        for image in images:
            if image.ndim > 2:
                raise ValueError("要合并子图像必须是单通道图像，不能是多通道图像")

        merged_image = np.stack(images, axis=-1)

        logging.info("成功合并图像通道")
        return merged_image
    except Exception as e:
        raise ValueError(f"在合并图像通道时发生错误： {e}")
